package com.shanghai.shanghaielectric.UI.basefragment;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

import com.shanghai.shanghaielectric.R;

import java.io.Serializable;

/**
 * Created by admin on 2018/1/9.
 */

public class BaseFragment extends Fragment {
    public static final String FRAGMENT_TAG_KEY = "fragment.tag";
    public static final String FRAGMENT_STACKNAME = "fragment.stackName";
    public static final int REQUEST_SIZE = 10;
    public static final int FIRST = 1;
    public static final int REFRESH = 2;
    public static final int MORE = 3;

    private String mLastStackName;
    private Serializable mParams;

//    private LoadingPage mLoadingPage;  //加载的三个点   是一个加载页（过渡用）
    private boolean isLoadingPageShown;
    private int mLoadingPageParentId = View.NO_ID;

    public Serializable getParams() {
        return mParams;
    }

    public void setParam(Serializable params) {
        this.mParams = params;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (mParams != null) {
            outState.putSerializable("SerializableParams", mParams);
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            mParams = savedInstanceState.getSerializable("SerializableParams");
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (isLoadingPageShown) {
//            displayLoadingPage(mLoadingPageParentId);//不需要加载页
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Fragment fragment = getTargetFragment();
        if (fragment != null && fragment instanceof BaseFragment) {
            BaseFragment targetFragment = (BaseFragment) fragment;
            targetFragment.onFragmentResult(getTargetRequestCode());
        }
//        removeLoadingPage();
//		if (getView() != null) {
//			Log.e("777","00000");
//			((ViewGroup) getView()).removeAllViews();
//		}
    }

    protected void onFragmentResult(int targetRequestCode) {
    }

    protected void onReload(Context context) {
    }

    public boolean onBackPressed() {
        return false;
    }

    public void onKeyDown(int keyCode, KeyEvent event) {
    }

    public void startFragment(Fragment fragment) {
        startFragment(fragment, null, null, null);
    }

    public void startFragment(Fragment fragment, String stackName) {
        startFragment(fragment, null, stackName, null);
    }

    public void startFragment(Fragment fragment, String stackName, boolean aminEnable) {
        startFragment(fragment, null, stackName, null, aminEnable);
    }

    public void startFragment(Fragment fragment, Bundle args) {
        startFragment(fragment, args, null, null);
    }

    public void startFragment(Fragment fragment, Bundle args, String tag) {
        startFragment(fragment, args, null, tag);
    }

    //R.id.main是 SVG 的 activity_main.xml 的id；显示的主界面  这里需要替换成 APF的 显示界面（是monitor_base_fragment的吗？待证！）
    public void startFragment(Fragment fragment, String stackName, boolean aminEnable, boolean finishLastFragment) {
        startFragment(fragment, R.id.main, null, stackName, null, aminEnable, finishLastFragment);
    }

    public void startFragment(Fragment fragment, Bundle args, boolean finishLastFragment) {
        startFragment(fragment, R.id.main, args, null, null, true, finishLastFragment);
    }

    public void startFragment(Fragment fragment, Bundle args, String stackName, String tag) {
        startFragment(fragment, R.id.main, args, stackName, tag, true, true);
    }

    public void startFragment(Fragment fragment, Bundle args, String stackName, String tag, boolean aminEnable) {
        startFragment(fragment, R.id.main, args, stackName, tag, aminEnable, true);
    }

    public void startFragment(Fragment fragment, int layoutId, Bundle args, String stackName, String tag, boolean aminEnable,
                              boolean finishLastFragment) {
        if (!TextUtils.isEmpty(mLastStackName)) {
            if (finishLastFragment) {
                this.finishFragment(mLastStackName);
            }
            mLastStackName = null;
        }
        if (args == null) {
            args = new Bundle();
        }
        if (stackName == null) {
            stackName = fragment.getClass().getName();
        }
        args.putString(FRAGMENT_STACKNAME, stackName);
        mLastStackName = stackName;
//        Activity activity = getActivity();
        FragmentActivity activity = getActivity();
        if (activity != null) {
//            FragmentManager fragmentManager = activity.getFragmentManager();//下面的FragmentManager全都换成了 support.v4.app
            android.support.v4.app.FragmentManager fragmentManager = activity.getSupportFragmentManager();
            android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
            fragment.setArguments(args);
            if (aminEnable) {
                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            }
            transaction.add(layoutId, fragment, tag);
            transaction.addToBackStack(stackName);
            transaction.commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
    }

    public void finishFragment() {
        Activity activity = getActivity();
        if (activity != null) {
            activity.getFragmentManager().popBackStackImmediate();
        }
    }

    public void finishFragment(String name) {
        Activity activity = getActivity();
        if (activity != null) {
            activity.getFragmentManager().popBackStackImmediate(name, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }

    public String getLastStackName() {
        return mLastStackName;
    }

//    加载页不需要
/*    public void showLoadingPage(String loadingText) {
        showLoadingPage(View.NO_ID,loadingText);
    }

    public void showLoadingPage(int layoutId,String loadingText) {
        closeLoadingPage();
        if (!isLoadingPageShown) {
            isLoadingPageShown = true;
            if (mLoadingPage == null) {
                mLoadingPage = createLoadingPage();
            }
            mLoadingPageParentId = layoutId;
            mLoadingPage.loading(loadingText);
            displayLoadingPage(layoutId);
        }
    }

    public void closeLoadingPage() {
        isLoadingPageShown = false;
        removeLoadingPage();
    }

    private void removeLoadingPage() {
        if (mLoadingPage != null) {
            ViewGroup parent = (ViewGroup) mLoadingPage.getParent();
            if (parent != null) {
                parent.removeView(mLoadingPage);
            }
        }
    }

    private boolean displayLoadingPage(int layoutId) {
        return displayView(mLoadingPage, layoutId);
    }

    private LoadingPage createLoadingPage() {
        final Context context = getActivity();
        LoadingPage loadingPage = new LoadingPage(context);
        return loadingPage;
    }*/

    private boolean displayView(View view, int layoutId) {
        ViewGroup layout = null;
        View rootView = getView();
        if (rootView != null && view != null) {
            int index = -1;
            if (layoutId != View.NO_ID) {
                layout = (ViewGroup) rootView.findViewById(layoutId);
                if (layout instanceof LinearLayout) {
                    index = 0;
                }
            } else {
                layout = ((ViewGroup) rootView);
            }
            if (layout != null) {
                layout.addView(view, index, new LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            }
        }
        return layout != null;
    }

}

